import React, { useCallback, useEffect, useState } from 'react'
import { View, Textarea, Text } from '@tarojs/components'
import SurveyHeader from './SurveyHeader'
import styles from './SurveyInput.module.scss'
const MAX_LENGTH = 200

const SurveyInput = ({
  data, language, onChange, submitted, ordinal, questionType
}) => {
  const { AnswerText } = data
  const [text, setText] = useState(AnswerText || '')
  const onChangeText = useCallback(e => {
    const val = e.detail.value
    onChange({ ...data, AnswerText: val })
    setText(val)
  }, [data, onChange])
  useEffect(() => {
    setText(AnswerText)
  }, [AnswerText, setText])
  const { QuestionText, Required } = data
  return (
    <View className={styles.container}>
      <SurveyHeader
        label={QuestionText?.[language]}
        questionType={questionType}
        ordinal={ordinal}
        required={Required}
      />
      <View className={styles.inputContainer}>
        {submitted
          ? (
            <Text className={`${styles.input} ${styles.submitted}`}>
              {text || '未填写'}
            </Text>
          ) : (
            <Textarea
              maxlength={MAX_LENGTH}
              placeholder="请输入，最多200字"
              placeholderClass={styles.placeholderText}
              className={styles.input}
              value={text}
              onInput={onChangeText}
            />
          )}
      </View>
    </View>
  )
}

export default SurveyInput
